// pages/invitefriends/invitefriends.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,   //海报的弹出层是否展示
    avatarUrl: 'https://wagoxcx.oss-cn-beijing.aliyuncs.com/image/defaultAvatar.png',   //头像的url
    nickname: '',   //名字
    name: '',   //生成海报的名字
    // 二维码
    codeImg: "",    //个人海报上的二维码
    cardBase: {
      //需要https图片路径,下载到本地然后去绘制    海报的背景图
      cardbg: "https://wagoxcx.oss-cn-beijing.aliyuncs.com/image/haibao.png",
      // cardbg: "../../images/signIn/invitation.png",
    },
    friendsList: [],
    count: '',   //获取的电力值

  },
  // 查看已经邀请的好友
  alreadyfriends() {
    var that = this
    wx.request({
      url: getApp().globalData.baseUrl + '/wago/user/selectByParentUserid',
      data: {
        userid: getApp().globalData.openid
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function (res) {
        // success
        if (res.data.flag) {
          that.setData({
            friendsList: res.data.data
          })
        }
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
  // 弹框展示
  showPopup() {
    this.setData({ show: true });
    this.getposterMessage()    //获取海报的二维码
    this.getAvaterInfo()   //获取用户信息
  },
  // 关闭海报的弹出层
  onClose() {
    this.setData({ show: false });
  },
  // 获取个人信息(头像和昵称、等级)
  getpersonalData: function () {
    var that = this;
    wx.request({
      url: getApp().globalData.baseUrl + '/wago/user/selectByOpenid',
      data: {
        openid: getApp().globalData.openid
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function (res) {
        // console.log('海报',res.data.data)
        // success
        if (res.data.flag) {
          that.setData({
            avatarUrl: res.data.data.headimgurl,
            nickname: res.data.data.nickname,
            grade: res.data.data.grade
          })
        }
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
  /**
   * 先下载海报背景
   */
  getAvaterInfo: function () {
    wx.showLoading({
      title: '生成中...',
      mask: true,
    });
    var that = this;
    wx.downloadFile({
      url: that.data.cardBase.cardbg,
      success: function (res) {
        wx.hideLoading();
        if (res.statusCode === 200) {
          //download下载成功返回结果res.tempFilePath
          var cardbg = res.tempFilePath;
          that.getQrCode(cardbg);
        } else {
          wx.showToast({
            title: '亲,海报下载失败！',
            icon: 'none',
            duration: 2000,
            success: function () {
              var cardbg = "";
              that.getQrCode(cardbg);
            }
          })
        }
      }
    })
  },
  // 获取电力值
  dianlizhi: function () {
    var that = this
    wx.request({
      url: getApp().globalData.baseUrl + '/wago/jifen/findById',
      data: {
        userid: getApp().globalData.openid
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      success: function (res) {
        // success
        if (res.data) {
          that.setData({
            count: res.data.data.zongjifen
          })
        }
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
  //获取海报上的二维码
  getposterMessage: function () {
    var that = this;
    wx.request({
      url: getApp().globalData.baseUrl + '/wago/user/getQRCode',
      data: {
        userid: getApp().globalData.openid
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      }, // 设置请求的 header
      success: function (res) {
        // success
        if (res.data.flag) {
          that.setData({
            codeImg: res.data.data
          })
          // console.log('海报的二维码',that.data.codeImg)
          // console.log('海报的头像',that.data.avatarUrl)
          that.getAvaterInfo()

          // that.getCanvas(that.data.cardBase.cardbg,that.data.codeImg,that.data.avatarUrl);   //绘制海报   背景图   二维码   头像图

        } else {
          that.$message.error('海报生成失败！')
        }
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
  // 获取个人信息(头像和昵称、等级)
  getpersonalData: function () {
    var that = this;
    wx.request({
      url: getApp().globalData.baseUrl + '/wago/user/selectByOpenid',
      data: {
        openid: getApp().globalData.openid
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function (res) {
        // console.log('海报',res.data.data)
        // success
        if (res.data.flag) {
          that.setData({
            avatarUrl: res.data.data.headimgurl,
            nickname: res.data.data.nickname,
            grade: res.data.data.grade
          })
        }
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
    this.getdianlizhi()    //获取电力值
  },

  // 获取电力值
  getdianlizhi: function () {
    var that = this
    wx.request({
      url: getApp().globalData.baseUrl + '/wago/jifen/findById',
      data: {
        userid: getApp().globalData.openid
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      success: function (res) {
        // success
        if (res.data) {
          that.setData({
            count: res.data.data.jifen
          })
        }
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
  // 去签到等的页面跳转
  todetail: function (e) {
    // console.log(e.currentTarget.dataset.url)
    wx.navigateTo({
      url: e.currentTarget.dataset.url
    })
  },
  // 跳转到浏览记录页面
  browseRecords: function () {
    wx.navigateTo({
      url: "/pages/browseRecords/browseRecords"
    })
  },
  // 跳转到我的收藏
  mycollection: function () {
    wx.navigateTo({
      url: "/pages/mycollection/mycollection"
    })
  },
  // 跳转到个人资料页面
  personalData: function () {
    wx.navigateTo({
      url: "/pages/personalData/personalData"
    })
  },
  // 弹框展示
  showPopup() {

    var that = this;
    var userid = getApp().globalData.openid
    if (userid) {
      this.setData({ show: true });
      that.getposterMessage()    //获取海报的二维码
      
    } else {
      wx.showToast({
        title: '请先登录!',
        icon: 'none'
      })
    }


  },
  // 关闭海报的弹出层
  onClose() {
    this.setData({ show: false });
  },
  /**
   * 先下载海报背景
   */
  getAvaterInfo: function () {
    wx.showLoading({
      title: '生成中...',
      mask: true,
    });
    var that = this;
    wx.downloadFile({
      url: that.data.cardBase.cardbg,
      success: function (res) {
        wx.hideLoading();
        if (res.statusCode === 200) {
          //download下载成功返回结果res.tempFilePath
          var cardbg = res.tempFilePath;
          that.getQrCode(cardbg);
        } else {
          wx.showToast({
            title: '亲,海报下载失败！',
            icon: 'none',
            duration: 2000,
            success: function () {
              var cardbg = "";
              that.getQrCode(cardbg);
            }
          })
        }
      }
    })
  },

  /**
   * 下载二维码图片
   */
  getQrCode: function (cardbg) {
    wx.showLoading({
      title: '生成中...',
      mask: true,
    });
    var that = this;
    wx.downloadFile({
      url: that.data.codeImg,
      success: function (res) {
        wx.hideLoading();
        if (res.statusCode === 200) {
          var codeImg = res.tempFilePath;
          that.getQravatar(cardbg, codeImg);
        } else {
          wx.showToast({
            title: '二维码下载失败！',
            icon: 'none',
            duration: 2000,
            success: function () {
              var codeImg = "";
              that.getQravatar(cardbg, codeImg);
            }
          })
        }
      }
    })

  },
  // 下载头像图片
  getQravatar: function (cardbg, codeImg) {
    wx.showLoading({
      title: '生成中...',
      mask: true,
    });
    var that = this
    // 下载头像图片
    wx.downloadFile({
      url: that.data.avatarUrl,
      success: function (res) {
        wx.hideLoading();
        if (res.statusCode === 200) {
          var avatarUrl = res.tempFilePath;
          that.getCanvas(cardbg, codeImg, avatarUrl);
        } else {
          wx.showToast({
            title: '头像下载失败！',
            icon: 'none',
            duration: 2000,
            success: function () {
              var avatarUrl = "";
              that.getCanvas(cardbg, codeImg, avatarUrl);
            }
          })
        }
      }
    })
  },
  /**
   * 开始用canvas绘制分享海报
   * @param cardbg 下载的海报背景图路径
   * @param codeImg   下载的二维码图片路径
   * @param avatarUrl    下载的头像的图片
   */
  getCanvas: function (cardbg, codeImg, avatarUrl) {
    wx.showLoading({
      title: '正在生成中...',
      mask: true,
    })
    var that = this;
    var cardBase = that.data.cardBase; //需要绘制的数据集合
    const ctx = wx.createCanvasContext('myCanvas'); //创建画布
    var width = "";
    wx.createSelectorQuery().select('#canvas-container').boundingClientRect(function (rect) {
      var height = rect.height;
      var right = rect.right;
      width = rect.width * 0.8;
      var left = rect.left + 5;
      ctx.setFillStyle('#fff');
      ctx.fillRect(0, 0, rect.width, height);
      // 这里处理自适应
      let rpx = 1;
      wx.getSystemInfo({
        success(res) {
          rpx = res.windowWidth / 375;
        },
      })

      //背景图
      if (cardbg) {
        ctx.drawImage(cardbg, 0 * rpx, 0 * rpx, 300 * rpx, 500 * rpx);
      }
      // 标题
      ctx.setFontSize(14);
      ctx.setFillStyle('#000');
      ctx.setTextAlign('left');
      ctx.fillText(that.data.nickname, 80 * rpx, 70 * rpx, 100 * rpx, 100 * rpx); //姓名
      //  绘制二维码
      if (codeImg) {
        ctx.drawImage(codeImg, 188 * rpx, 367 * rpx, 65 * rpx, 65 * rpx)
      }
      // 绘制头像
      if (avatarUrl) {
        ctx.drawImage(avatarUrl, 40 * rpx, 45 * rpx, 33 * rpx, 33 * rpx)
      }

    }).exec()

    setTimeout(function () {
      ctx.draw();
      wx.hideLoading();
    }, 1000)

  },

  //长按保存到相册
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success(res) {
              console.info(res);
              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  if (res.confirm) { }
                },
                fail: function (res) { }
              })
            },
            fail: function (res) {
              console.log(res)
              if (res.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                console.log("打开设置窗口");
                wx.openSetting({
                  success(settingdata) {
                    console.log(settingdata)
                    if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                      console.log("获取权限成功，再次点击图片保存到相册")
                    } else {
                      console.log("获取权限失败")
                    }
                  }
                })
              }
            }
          })
        }
      });
    }, 1000);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.alreadyfriends()    //获取已经邀请的好友列表数据
    this.getpersonalData() // 获取个人信息(头像和昵称、等级)
    this.dianlizhi()   //获取电力值
  },

})